import json
import re
import time

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

from django.shortcuts import render
# from data.itemList import context as itemContext
from data.cartItems import context as cartContxt
from items.models import ItemList, Pay_log
from user.models import UserList


def index(request):
    if request.method == 'POST':
        print(request.body)
        items = []
        shops = re.findall('shopid=(\\d)\\*(\\d)', str(request.body))
        for shop in shops:
            item = ItemList.objects.get(id=shop[0])
            if item:
                item.buy_count = shop[1]
                items.append(item)
        # for itemIdx in cartContxt.keys():
        #     item = ItemList.objects.get(id=itemIdx)
        #     item.count -= cartContxt[itemIdx]['count']
        #     item.save()
        #
        #
        # cartContxt.clear()
    return render(request, 'pay/success.html', {'items': items})


def buy(request):
    if request.method == 'POST':
        json_data = json.loads(request.body.decode('utf-8'))
        for item in json_data['shops']:
            Pay_log.objects.create(
                user=UserList.objects.get(id=1),
                item=ItemList.objects.get(id=item['id']),
                quantity=item['count'],
                name=json_data['name'],
                address=json_data['address'],
                phone=json_data['phone'],
                ps=json_data['beizhu'],
                # create_time=
            )
        # for itemIdx in cartContxt.keys():
        #     item = ItemList.objects.get(id=itemIdx)
        #     item.count -= cartContxt[itemIdx]['count']
        #     item.save()
        # cartContxt.clear()
    return HttpResponse('<script>alert(\"购买成功\");window.location.href(\'\')</script>')


def pay_log(request):
    items = Pay_log.objects.filter(user__id=1)
    return render(request, 'pay/log.html', context={'items': items})
